package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.CategoryDTO;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.YzjData;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.YzjMapper;
import com.sky.result.HttpClientUtils;
import com.sky.result.PageResult;
import com.sky.service.CategoryService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 分类业务层
 */
@Service
@Slf4j
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    YzjMapper yzjMapper;

    ExecutorService cachedThreadPool = Executors.newCachedThreadPool();

    /**
     * 新增分类
     * @param categoryDTO
     */
    public void save(CategoryDTO categoryDTO) {
        Category category = new Category();
        //属性拷贝
        BeanUtils.copyProperties(categoryDTO, category);

        //分类状态默认为禁用状态0
        category.setStatus(StatusConstant.DISABLE);

        //设置创建时间、修改时间、创建人、修改人
        //category.setCreateTime(LocalDateTime.now());
        //category.setUpdateTime(LocalDateTime.now());
        //category.setCreateUser(BaseContext.getCurrentId());
        //category.setUpdateUser(BaseContext.getCurrentId());

        categoryMapper.insert(category);
    }

    /**
     * 分页查询
     * @param categoryPageQueryDTO
     * @return
     */
    public PageResult pageQuery(CategoryPageQueryDTO categoryPageQueryDTO) {
        PageHelper.startPage(categoryPageQueryDTO.getPage(),categoryPageQueryDTO.getPageSize());
        //下一条sql进行分页，自动加入limit关键字分页
        Page<Category> page = categoryMapper.pageQuery(categoryPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 根据id删除分类
     * @param id
     */
    public void deleteById(Long id) {
        //查询当前分类是否关联了菜品，如果关联了就抛出业务异常
        Integer count = dishMapper.countByCategoryId(id);
        if(count > 0){
            //当前分类下有菜品，不能删除
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_DISH);
        }

        //查询当前分类是否关联了套餐，如果关联了就抛出业务异常
        count = setmealMapper.countByCategoryId(id);
        if(count > 0){
            //当前分类下有菜品，不能删除
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_SETMEAL);
        }

        //删除分类数据
        categoryMapper.deleteById(id);
    }

    /**
     * 修改分类
     * @param categoryDTO
     */
    public void update(CategoryDTO categoryDTO) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO,category);

        //设置修改时间、修改人
        //category.setUpdateTime(LocalDateTime.now());
        //category.setUpdateUser(BaseContext.getCurrentId());

        categoryMapper.update(category);
    }

    /**
     * 启用、禁用分类
     * @param status
     * @param id
     */
    public void startOrStop(Integer status, Long id) {
        Category category = Category.builder()
                .id(id)
                .status(status)
                //.updateTime(LocalDateTime.now())
                //.updateUser(BaseContext.getCurrentId())
                .build();
        categoryMapper.update(category);
    }

    /**
     * 根据类型查询分类
     * @param type
     * @return
     */
    public List<Category> list(Integer type) {
        return categoryMapper.list(type);
    }

    @Override
    public List<YzjData> yzj() throws InterruptedException {
        List<YzjData> yzj = yzjMapper.getYzjAndFlag();
        if(yzj != null && yzj.size() > 0){
            String token = getToken();
            for (YzjData item : yzj) {
                String openid = item.getOpenid();
                getDataState(item.getId(),openid,token);

            }
        }
        return yzj;
    }


    public static String getToken(){
        String url = "https://cloud.nbport.com.cn/gateway/oauth2/token/getAccessToken";
        Map<String, String> map = new HashMap<>();
        map.put("appId","500000196");
        map.put("secret","ytYIdgMDKwLtyb5Nwxck");
        map.put("scope","app");
        map.put("timestamp",Long.toString(System.currentTimeMillis()));
        String str = null;
        try {
            str = HttpClientUtil.doPost(url, map);
            org.json.JSONObject json = new org.json.JSONObject(str);
            String token  =  json.getJSONObject("data").getString("accessToken");
            return token;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    public static String removeData(String dataId, String token){
        String url = "https://cloud.nbport.com.cn/gateway/newtodo/open/action.json?accessToken="+token;
        Map<String, String> map = new HashMap<>();
        map.put("sourceitemid",dataId);
        map.put("sourcetype","500000196");
        map.put("actiontype","{\"delete\":\""+1+"\"}");
        map.put("sync","true");
        String json = null;
        try {
            json = HttpClientUtil.doPost4Json(url, map);
            log.error("删除代办------>>>>>>"+json);
            return  json;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    public static String removeData2(String dataId, String token){
        String url = "https://cloud.nbport.com.cn/gateway/newtodo/open/action.json?accessToken="+token;

        Map<String, String> requestHeader = new HashMap<>();
        requestHeader.put("accept", "*/*");
        requestHeader.put("Content-Type", "application/json");

        Map<String, Object> map = new HashMap<>();
        map.put("sourceitemid",dataId);
        map.put("sourcetype","500000196");
        map.put("actiontype","{\"delete\":\""+1+"\"}");
        map.put("sync","true");
        try {
            String json = HttpClientUtils.doPost(url, requestHeader, map);
            log.error("删除代办---->>>>{}",json);
            return null;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    public  String getDataState(Long id,String openId,String token){
        // 查询代办状态
        String url = "https://cloud.nbport.com.cn/gateway/newtodo/open/checkcreatetodo.json?accessToken="+ token;
        Map<String, String> requestHeader = new HashMap<>();
        requestHeader.put("accept", "*/*");
        requestHeader.put("Content-Type", "application/json");
        Map<String, Object> map = new HashMap<>();
        map.put("sourceitemid","372590");
        map.put("sourcetype","500000196");
        map.put("openId","5de50017e4b0b2767b870423");
        try {
            String str = HttpClientUtils.doPost(url, requestHeader, map);
            org.json.JSONObject json = new org.json.JSONObject(str);
            JSONObject data = json.getJSONObject("data");
            int dealCount = json.getJSONObject("data").getInt("dealCount");
            int delCount = json.getJSONObject("data").getInt("undelCount");
            yzjMapper.updateFlag(id,dealCount,delCount);
            return null;
        } catch (Exception e) {
            try {
                Thread.sleep(3000);
                this.yzj();
            } catch (Exception ex) {
//                throw new RuntimeException(ex);
            }
            return null;
        }
    }

    public static void main(String[] args) throws Exception {
        String token = getToken();
        System.out.println("token--->>>" + token);
//        getDataState("372590",token);
//        removeData2("90454",token);

    }
}
